package com.tanhan.mindapp.exception;

import com.tanhan.mindapp.dao.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

// 所有的错误都会进到这个类
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理权限拒绝异常
     */
    @ExceptionHandler(value = {AccessDeniedException.class})
    @ResponseBody
    public Result accessDeniedHandler(AccessDeniedException e) {
        log.error("权限拒绝异常: {}", e.getMessage());
        return Result.error(401, "ACCESS DENIED");
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        //这里先判断拦截到的Exception是不是我们自定义的异常类型
        if (e instanceof AppException) {
            AppException appException = (AppException) e;
            log.error("自定义报错 {} {}", appException.getMsg(),e);
            return Result.error(appException.getCode(), appException.getMsg());
        }
        log.error("非自定义异常", e);
        //如果拦截的异常不是我们自定义的异常(例如：数据库主键冲突)
        return Result.error(500, "服务器端异常");
    }
}
